<?php

class Processdesigner extends Controller {

    function __construct()
    {
        parent::Controller();
    }
    
    // CREATE

    private function _checkAccess($process_id = false)
    {
        $this->load->model('processdesigner_model');
        $bool = FALSE;
        if($process_id)
        {
            $bool = $this->processdesigner_model->is_process_owner($this->session->userdata('user_id'), $process_id);
        }

        if($this->session->userdata('logged_in'))
        {
            return ($this->session->userdata('user_level') == PROCESS_MANAGER ||
                    $this->session->userdata('user_level') == ADMIN ||
                    $bool);
        }
        return FALSE;
    }
    
    private function _get_users_table($users, $selected_ids=array(), $num_cols=3)
    {
        $this->load->library('table');

        $tmpl = array ( 'table_open'  => '<table>' );
        $this->table->set_template($tmpl);

        $count = count($users);

        for($i = 0; $i < $count; $i += $num_cols)
        {
            $users_slice = array_slice($users, $i, $num_cols);
            $row = array();

            foreach($users_slice as $user)
            {
                $val = $user['firstname'].' '.$user['surname'];
                $id = $user['user_id'];
                $checked = in_array($id, $selected_ids) ? 'checked' : '';
                $row[] = '<label for="user'.$id.'">'.$val.'</label> <input type="checkbox" id="user'.$id.'" name="user'.$id.'" '.$checked.' />';
            }
            
            $this->table->add_row($row);
        }

        $table = $this->table->generate();
        $this->table->clear();
        $table = ($table == 'Undefined table data') ? 'There are no users' : $table;

        return $table;
    }

    private function _get_stages_table($stages, $selected_ids=array(), $num_cols=3)
    {
        $this->load->library('table');

        $tmpl = array ( 'table_open'  => '<table>' );
        $this->table->set_template($tmpl);

        $count = count($stages);

        for($i = 0; $i < $count; $i += $num_cols)
        {
            $stages_slice = array_slice($stages, $i, $num_cols);
            $row = array();

            foreach($stages_slice as $stage)
            {
                $val = $stage['stage_name'];
                $id = $stage['stage_id'];
                $checked = in_array($id, $selected_ids) ? 'checked' : '';
                $row[] = '<label for="stage'.$id.'">'.$val.'</label> <input type="checkbox" id="stage'.$id.'" name="stage'.$id.'" '.$checked.' />';
            }

            $this->table->add_row($row);
        }

        $table = $this->table->generate();
        $this->table->clear();
        $table = $table == 'Undefined table data' ? 'There are no previous stages' : $table;

        return $table;
    }

    private function _get_users_select($users, $selected_id='')
    {
        $select = '<select id="administrator" name="administrator">';
        foreach($users as $user)
        {
            $name = $user['firstname'].' '.$user['surname'];
            $id = $user['user_id'];
            $selected = $id == $selected_id ? 'selected="selected"' : '';
            $select = $select.'<option value="'.$id.'" '.$selected.' >'.$name.'</option>';
        }
        $select = $select.'</select>';
        return $select;
    }

    function _valid_admin($user_id)
    {
        $this->load->model('users_model');
        $this->form_validation->set_message('_valid_admin', 'The admin you have selected is not valid');
        return !($this->users_model->get_userdata($user_id) == FALSE);
    }

    function _valid_jointype($jointype)
    {
        $this->load->model('processdesigner_model');

        $stages = $this->processdesigner_model->all_stages();
        $selected_stages = array();
        foreach($stages as $stage)
        {
            if($this->input->post('stage'.$stage['stage_id']))
            {
                $selected_stages[] = $stage;
            }
        }

        $count = count($selected_stages);
        if($jointype == 'AND')
        {
            if($count < 2)
            {
                $this->form_validation->set_message('_valid_jointype', 'The AND Join type requires you to have selected at least 2 previious stages');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
        else if($jointype == 'OR')
        {
            if($count < 2)
            {
                $this->form_validation->set_message('_valid_jointype', 'The OR Join type requires you to have selected at least 2 previious stages');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
        else if($jointype == 'NONE')
        {
            if($count > 1)
            {
                $this->form_validation->set_message('_valid_jointype', 'The NONE Join type requires you to have selected 0 or 1 previous stages');
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
        else
        {
            $this->form_validation->set_message('_valid_jointype', 'Invalid Join type selected');
            return TRUE;
        }
    }

    function _valid_splittype($splittype)
    {
        switch($splittype)
        {
            case 'AND':
            case 'OR':
            case 'NONE':
                return TRUE;
            default:
                $this->form_validation->set_message('_valid_splittype', 'Invalid Split type selected');
                return FALSE;
        }
    }

    function _valid_attribute_type($attribute_type)
    {
        switch($attribute_type)
        {
            case 'TEXT':
            case 'PASSWORD':
            case 'TEXTAREA':
            case 'CHECKBOX':
            case 'FILE':
                return TRUE;
            default:
                $this->form_validation->set_message('_valid_attribute_type', 'Invalid %s');
                return FALSE;
        }
    }

    function create_process() 
    {        
        if(!$this->_checkAccess())
        {
            redirect('home');
        }
        $this->load->model('users_model');
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('process_rules') == FALSE)
        {
            $name = $this->input->post('name') ? $this->input->post('name') : '';
            $description = $this->input->post('description') ? $this->input->post('description') : '';
            
            $users = $this->users_model->all_users();
            $selected_ids = array();

            foreach($users as $user)
            {
                if($this->input->post('user'.$user['user_id']))
                {
                    $selected_ids[] = $user['user_id'];
                }
            }
            
            $users_table = $this->_get_users_table($users, $selected_ids);

            $selected_id = $this->input->post('administrator') ? $this->input->post('administrator') : '';
            $users_select = $this->_get_users_select($users, $selected_id);

            $this->load->view('template/standard', array(
                'title'     => 'Create a new process',
                'content'   => $this->load->view('processdesigner/editor_process',
                        array(
                            'action'       => 'processdesigner/create_process',
                            'name'         => $name,
                            'description'  => $description,
                            'users_table'  => $users_table,
                            'users_select' => $users_select,
                            'location'     => 'home/main'
                ), TRUE)
            ));
        }
        else
        {
            $this->load->model('processdesigner_model');

            $name = $this->input->post('name');
            $description = $this->input->post('description');
            $admin = $this->input->post('administrator');
            $owners = array();
            $users = $this->users_model->all_users();

            foreach($users as $user)
            {
                if($this->input->post('user'.$user['user_id']) && $user['user_id'] != $admin)
                {
                    $owners[] = $user['user_id'];
                }
            }

            $process_id = $this->processdesigner_model->insert_process($name, $description, $admin, $owners);
            redirect("processdesigner/view_process/{$process_id}");
        }
    }

    function create_stage($process_id)
    {        
        if(!$this->_checkAccess($process_id))
        {
            redirect('home');
        }
        $this->load->model('users_model');
        $this->load->model('processdesigner_model');

        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('stage_rules') == FALSE)
        {
            $name = $this->input->post('name') ? $this->input->post('name') : '';
            $description = $this->input->post('description') ? $this->input->post('description') : '';


            $stages = $this->processdesigner_model->get_stages($process_id);
            $selected_ids = array();

            foreach($stages as $stage)
            {
                if($this->input->post('stage'.$stage['stage_id']))
                {
                    $stage_ids[] = $stage['stage_id'];
                }
            }

            $stages_table = $this->_get_stages_table($stages, $selected_ids);


            $users = $this->users_model->all_users();
            $selected_ids = array();

            foreach($users as $user)
            {
                if($this->input->post('user'.$user['user_id']))
                {
                    $selected_ids[] = $user['user_id'];
                }
            }

            $users_table = $this->_get_users_table($users, $selected_ids);

            $selected_id = $this->input->post('administrator') ? $this->input->post('administrator') : '';
            $users_select = $this->_get_users_select($users, $selected_id);

            $this->load->view('template/standard', array(
                'title'     => 'Create a new stage',
                'content'   => $this->load->view('processdesigner/editor_stage',
                        array(
                            'action'       => "processdesigner/create_stage/{$process_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'stages_table' => $stages_table,
                            'users_table'  => $users_table,
                            'users_select' => $users_select,
                            'location'     => "processdesigner/view_process/{$process_id}"
                ), TRUE)
            ));
        }
        else
        {
            $this->load->model('processdesigner_model');

            $name = $this->input->post('name');
            $description = $this->input->post('description');
            $previous_stages = array();
            $stages = $this->processdesigner_model->get_stages($process_id);
            foreach($stages as $stage)
            {
                if($this->input->post('stage'.$stage['stage_id']))
                {
                    $previous_stages[] = $stage['stage_id'];
                }
            }

            $jointype = $this->input->post('jointtype');
            switch($jointype)
            {
                case 'AND':
                    $jointype = JOIN_TYPE_AND;
                    break;
                case 'OR':
                    $jointype = JOIN_TYPE_OR;
                    break;
                case 'NONE';
                    $jointype = JOIN_TYPE_NONE;
                    break;
                default:
                    $jointype = JOIN_TYPE_NONE;
                    break;
            }

            $splittype = $this->input->post('splittype');
            switch($splittype)
            {
                case 'AND':
                    $splittype = SPLIT_TYPE_AND;
                    break;
                case 'OR':
                    $splittype = SPLIT_TYPE_OR;
                    break;
                case 'NONE':
                   $splittype = SPLIT_TYPE_NONE;
                   break;
                default:
                    $splittype = SPLIT_TYPE_NONE;
                    break;
            }

            $admin = $this->input->post('administrator');
            $participants = array();
            $users = $this->users_model->all_users();

            foreach($users as $user)
            {
                if($this->input->post('user'.$user['user_id']) && $user['user_id'] != $admin)
                {
                    $participants[] = $user['user_id'];
                }
            }

            $stage_id = $this->processdesigner_model->insert_stage($process_id, $name, $description,
                                    $previous_stages, $jointype, $splittype, $admin, $participants);

            redirect("processdesigner/view_process/{$process_id}");
        }
    }

    function create_contribution($stage_id) 
    {
        $this->load->model('processdesigner_model');
        
        $process = $this->processdesigner_model->get_owner_process($stage_id);
        
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }
        
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('contribution_rules') == FALSE)
        {
            $name = $this->input->post('name') ? $this->input->post('name') : '';
            $description = $this->input->post('description') ? $this->input->post('description') : '';

            $this->load->view('template/standard', array(
                'title'     => 'Create a new contribution',
                'content'   => $this->load->view('processdesigner/editor_contribution',
                        array(
                            'action'       => "processdesigner/create_contribution/{$stage_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'location'     => "processdesigner/view_stage/{$stage_id}"
                ), TRUE)
            ));
        }
        else
        {
            $name = $this->input->post('name');
            $description = $this->input->post('description');

            $this->processdesigner_model->insert_contribution($stage_id, $name, $description);
            redirect("processdesigner/view_stage/{$stage_id}");
        }
    }

    function create_attribute($contribution_id)
    {
        $this->load->model('processdesigner_model');

        $stage = $this->processdesigner_model->get_owner_stage($contribution_id);

        if(!$stage)
        {
            redirect('home/main');
        }

        $process = $this->processdesigner_model->get_owner_process($stage['stage_id']);

        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }

        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('attribute_rules') == FALSE)
        {
            $name = $this->input->post('name') ? $this->input->post('name') : '';
            $description = $this->input->post('description') ? $this->input->post('description') : '';
            $checked = $this->input->post('optional') ? 'checked="ckecked"' : '';

            $this->load->view('template/standard', array(
                'title'     => 'Create a new attribute',
                'content'   => $this->load->view('processdesigner/editor_attribute',
                        array(
                            'action'       => "processdesigner/create_attribute/{$contribution_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'checked'      => $checked,
                            'location'     => "processdesigner/view_contribution/{$contribution_id}"
                ), TRUE)
            ));
        }
        else
        {
            $name = $this->input->post('name');
            $description = $this->input->post('description');
            $type = $this->input->post('attribute_type');
            $optional = $this->input->post('optional') ? 1 : 0;

            $this->processdesigner_model->insert_attribute($contribution_id, $name, $description, $type, $optional);
            redirect("processdesigner/view_contribution/{$contribution_id}");
        }
    }

    /*************************************************************************/

    // VIEW

    function view_process($process_id)
    {
        if(!$this->_checkAccess($process_id))
        {
            redirect('home');
        }

        $this->load->model('processdesigner_model');
        $process = $this->processdesigner_model->get_processdata($process_id);

        $stages = $this->processdesigner_model->get_stages($process_id);
        $table = FALSE;

        if(count($stages) > 0)
        {
            $this->load->library('table');
            $tmpl = array ( 'table_open'  => '<table>' );
            $this->table->set_template($tmpl);
            foreach($stages as $stage)
            {
                $join = $stage['join_type'];
                switch($join)
                {
                    case NULL:
                        $join = '';
                        break;
                    case JOIN_TYPE_AND:
                        $join = 'join type: AND; ';
                        break;
                    case JOIN_TYPE_OR:
                        $join = 'join type: OR; ';
                        break;
                    default:
                        $join = '';
                        break;
                }

                $previous = '';
                $previous_stages = $this->processdesigner_model->previous_stages($stage['stage_id']);

                if($previous_stages)
                {
                    $previous = 'Previous stages: ';
                    $n = count($previous_stages);
                    for($i = 0; $i < $n - 1; $i++)
                    {
                        $previous = $previous.$previous_stages[$i]['stage_name'].', ';
                    }
                    $previous = $previous.$previous_stages[$n - 1]['stage_name'].'; ';
                }

                $split = $stage['split_type'];
                switch($split)
                {
                    case NULL:
                        $split = '';
                        break;
                    case SPLIT_TYPE_AND:
                        $split = 'split type: AND; ';
                        break;
                    case SPLIT_TYPE_OR:
                        $split = 'split type: OR; ';
                        break;
                    default:
                        $split = '';
                        break;
                }

                $row = array();
                $info = $stage['stage_name'].' ('.$join.$previous.$split.')';
                $row[] = $info;
                $row[] = anchor("processdesigner/view_stage/{$stage['stage_id']}", 'view details');
                $row[] = anchor("processdesigner/edit_stage/{$stage['stage_id']}", 'edit');
                $row[] = anchor("processdesigner/delete_stage/{$stage['stage_id']}", 'delete', array('onclick' => "javascript:confirm('Are you sure you want to delete this stage?')"));
                $this->table->add_row($row);
            }
            $table = $this->table->generate();
        }

        $attributes = array();

        $attributes[] = array(
            'label'    => 'Process name',
            'content'  => $process['process_name']
        );

        $attributes[] = array(
            'label'   => 'Process description',
            'content' => $process['process_description']
        );

        $data = array(
            'title'      => $process['process_name'],
            'attributes' => $attributes
        );

        if($table)
        {
            $data['content_type'] = 'stages';
            $data['content_table'] = $table;
        }

        $this->load->view('template/standard', array(
            'title'      => 'Design process',
            'content'    => $this->load->view('processdesigner/view_details', $data, TRUE),
            'menu_items' => array(
                site_url("home/start_process/{$process_id}")             => 'Start process',
                site_url("processdesigner/edit_process/{$process_id}")   => 'Edit process details',
                site_url("processdesigner/delete_process/{$process_id}") => 'Delete process',
                site_url("processdesigner/create_stage/{$process_id}")   => 'Add new stage'
            )
        ));
    }

    function view_stage($stage_id) 
    {
        $this->load->model('processdesigner_model');
        $process = $this->processdesigner_model->get_owner_process($stage_id);

        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home');
        }

        $stage = $this->processdesigner_model->get_stagedata($stage_id);

        $contributions = $this->processdesigner_model->get_contributions($stage_id);
        $table = FALSE;

        if(count($contributions) > 0)
        {
            $this->load->library('table');
            $tmpl = array ( 'table_open'  => '<table>' );
            $this->table->set_template($tmpl);
            foreach($contributions as $contribution)
            {
                $row = array();
                $info = $contribution['contribution_title'];
                $row[] = $info;
                $row[] = anchor("processdesigner/view_contribution/{$contribution['contribution_id']}", 'view details');
                $row[] = anchor("processdesigner/edit_contribution/{$contribution['contribution_id']}", 'edit');
                $row[] = anchor("processdesigner/delete_contribution/{$contribution['contribution_id']}", 'delete', array('onclick' => "javascript:confirm('Are you sure you want to delete this contribution?')"));
                $this->table->add_row($row);
            }
            $table = $this->table->generate();
        }

        $attributes = array();

        $attributes[] = array(
            'label'    => 'Stage name',
            'content'  => $stage['stage_name']
        );

        $attributes[] = array(
            'label'   => 'Stage description',
            'content' => $stage['stage_description']
        );
        
        $splittype = $stage['split_type'];

        if($splittype === SPLIT_TYPE_AND)
        {
            $splittype = 'AND';
        }
        else if($splittype === SPLIT_TYPE_OR)
        {
            $splttype = 'OR';
        }
        else
        {
            $splittype = '---';
        }

        $attributes[] = array(
            'label'   => 'Split type',
            'content' => $splittype
        );

        $jointype = $stage['join_type'];

        if($jointype === JOIN_TYPE_AND)
        {
            $jointype = 'AND';
        }
        else if($jointype === JOIN_TYPE_OR)
        {
            $jointype = 'OR';
        }
        else
        {
            $jointype = '---';
        }
        
        $attributes[] = array(
            'label'   => 'Join type',
            'content' => $jointype
        );
        
        $previous_stages = $this->processdesigner_model->previous_stages($stage_id);
        $previous = '';
        foreach($previous_stages as $previous_stage)
        {
            $previous = $previous.$previous_stage['stage_name'].'; ';
        }
        $previous = $previous == '' ? 'None' : $previous;
        
        $attributes[] = array(
            'label'   => 'Previous stages',
            'content' => $previous
        );

        $data = array(
            'title'      => anchor("processdesigner/view_process/{$process['process_id']}", $process['process_name']).' > '.$stage['stage_name'],
            'attributes' => $attributes
        );

        if($table)
        {
            $data['content_type'] = 'contributions';
            $data['content_table'] = $table;
        }

        $this->load->view('template/standard', array(
            'title'      => 'Design process',
            'content'    => $this->load->view('processdesigner/view_details', $data, TRUE),
            'menu_items' => array(
                site_url("processdesigner/edit_stage/{$stage_id}")   => 'Edit stage details',
                site_url("processdesigner/create_contribution/{$stage_id}")   => 'Add new contribution'
            )
        ));
    }

    function view_contribution($contribution_id)
    {
        $this->load->model('processdesigner_model');
        $stage = $this->processdesigner_model->get_owner_stage($contribution_id);
        if(!$stage)
        {
            redirect('home/main');
        }
        $process = $this->processdesigner_model->get_owner_process($stage['stage_id']);
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }
        $contribution = $this->processdesigner_model->get_contributiondata($contribution_id);

        $attributes = $this->processdesigner_model->get_attributes($contribution_id);
        $table = FALSE;

        if(count($attributes) > 0)
        {
            $this->load->library('table');
            $tmpl = array ( 'table_open'  => '<table>' );
            $this->table->set_template($tmpl);

            foreach($attributes as $attribute)
            {
                $row = array();
                $row[] = $attribute['attribute_name'];
                $row[] = anchor("processdesigner/view_attribute/{$attribute['attribute_id']}", 'view details');
                $row[] = anchor("processdesigner/edit_attribute/{$attribute['attribute_id']}", 'edit');
                $row[] = anchor("processdesigner/delete_attribute/{$attribute['attribute_id']}", 'delete', array('onclick' => "javascript:confirm('Are you sure you want to delete this attribute?')"));
                $this->table->add_row($row);
            }
            $table = $this->table->generate();
        }

        $attributes = array();

        $attributes[] = array(
            'label'   => 'Contribution title',
            'content' => $contribution['contribution_title']
        );

        $attributes[] = array(
            'label'   => 'Description',
            'content' => $contribution['contribution_description']
        );

        $data = array(
            'title'      => anchor("processdesigner/view_process/{$process['process_id']}", $process['process_name']).
                            ' > '.anchor("processdesigner/view_stage/{$stage['stage_id']}", $stage['stage_name']).
                            ' > '.$contribution['contribution_title'],
            'attributes' => $attributes
        );

        if($table)
        {
            $data['content_type'] = 'attributes';
            $data['content_table'] = $table;
        }

        $this->load->view('template/standard', array(
            'title'      => 'Design process',
            'content'    => $this->load->view('processdesigner/view_details', $data, TRUE),
            'menu_items' => array(
                site_url("processdesigner/edit_contribution/{$contribution_id}")   => 'Edit contribution details',
                site_url("processdesigner/create_attribute/{$contribution_id}")   => 'Add new attribute'
            )
        ));
    }

    function view_attribute($attribute_id)
    {
        $this->load->model('processdesigner_model');
        $contribution = $this->processdesigner_model->get_owner_contribution($attribute_id);
        if(!$contribution)
        {
           redirect('home/main');
        }
        $stage = $this->processdesigner_model->get_owner_stage($contribution^'contribution_id');
        if(!$stage)
        {
            redirect('home/main');
        }
        $process = $this->processdesigner_model->get_owner_process($stage['stage_id']);
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }
        $attribute = $this->processdesigner_model->get_attributedata($attribute_id);
        
        $attributes = array();

        $attributes[] = array(
            'label'   => 'Attribute title',
            'content' => $attribute['attribute_name']
        );

        $attributes[] = array(
            'label'   => 'Description',
            'content' => $attribute['attribute_description']
        );

        $attributes[] = array(
            'label'   => 'Attribute type',
            'content' => $attribute['attribute_type'],
        );

        $optional = $attribute['optional'] == 1 ? 'yes' : 'no';

        $attributes[] = array(
            'label'   => 'optional',
            'content' => $optional
        );

        $data = array(
            'title'      => anchor("processdesigner/view_process/{$process['process_id']}", $process['process_name']).
                            ' > '.anchor("processdesigner/view_stage/{$stage['stage_id']}", $stage['stage_name']).
                            ' > '.anchor("processdesigner/view_contribution/{$contribution['contribution_id']}", $contribution['contribution_title']).
                            ' > '.$attribute['attribute_name'],
            'attributes' => $attributes
        );

        $this->load->view('template/standard', array(
            'title'      => 'Design process',
            'content'    => $this->load->view('processdesigner/view_details', $data, TRUE),
            'menu_items' => array(
                site_url("processdesigner/edit_attribute/{$attribute_id}")   => 'Edit attribute details',
            )
        ));
    }

    /*************************************************************************/

    // EDIT

    function edit_process($process_id)
    {
        $this->load->model('users_model');
        if(!$this->_checkAccess())
        {
            redirect('home');
        }

        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('process_rules') == FALSE)
        {
            $this->load->model('processdesigner_model');
            $process = $this->processdesigner_model->get_processdata($process_id);
            $name = $this->input->post('name') ? $this->input->post('name') : $process['process_name'];
            $description = $this->input->post('description') ? $this->input->post('description') : $process['process_description'];

            $users = $this->users_model->all_users();
            $process_owners = $this->processdesigner_model->get_process_owners($process_id);
            $selected_ids = array();

            foreach($process_owners as $user)
            {
                $selected_ids[] = $user['user_id'];
            }

            $users_table = $this->_get_users_table($users, $selected_ids);

            $admin = $this->processdesigner_model->get_process_admin($process_id);

            $selected_id = $this->input->post('administrator') ? $this->input->post('administrator') : $admin;
            $users_select = $this->_get_users_select($users, $selected_id);

            $this->load->view('template/standard', array(
                'title'     => 'Create a new process',
                'content'   => $this->load->view('processdesigner/editor_process',
                        array(
                            'action'       => "processdesigner/edit_process/{$process_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'users_table'  => $users_table,
                            'users_select' => $users_select,
                            'location'     => "processdesigner/view_process/{$process_id}"
                ), TRUE)
            ));
        }
        else
        {
            $this->load->model('processdesigner_model');

            $name = $this->input->post('name');
            $description = $this->input->post('description');
            $admin = $this->input->post('administrator');
            $owners = array();
            $users = $this->users_model->all_users();

            foreach($users as $user)
            {
                if($this->input->post('user'.$user['user_id']) && $user['user_id'] != $admin)
                {
                    $owners[] = $user['user_id'];
                }
            }

            $this->processdesigner_model->update_process($process_id, $name, $description, $admin, $owners);
            redirect("processdesigner/view_process/{$process_id}");
        }
    }

    function edit_stage($stage_id)
    {
        $this->load->model('users_model');
        $this->load->model('processdesigner_model');

        $process = $this->processdesigner_model->get_owner_process($stage_id);
        
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home');
        }

        $process_id = $process['process_id'];

        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        $stage = $this->processdesigner_model->get_stagedata($stage_id);

        if($this->form_validation->run('stage_rules') == FALSE)
        {
            $name = $this->input->post('name') ? $this->input->post('name') : $stage['stage_name'];
            $description = $this->input->post('description') ? $this->input->post('description') : $stage['stage_description'];


            $stages = $this->processdesigner_model->get_stages($process_id);
            $previous_stages = $this->processdesigner_model->previous_stages($stage_id);
            $selected_ids = array();

            foreach($previous_stages as $stage)
            {
                $stage_ids[] = $stage['stage_id'];
            }

            $stages_table = $this->_get_stages_table($stages, $selected_ids);


            $users = $this->users_model->all_users();
            $stage_participants = $this->processdesigner_model->stage_participants($stage['stage_id']);
            $selected_ids = array();

            foreach($stage_participants as $user)
            {
                $selected_ids[] = $user['user_id'];
            }

            $users_table = $this->_get_users_table($users, $selected_ids);

            $admin = $this->processdesigner_model->stage_participants($stage_id, STAGE_ADMIN);
            $admin_id = 0;

            if(count($admin) > 0)
            {
                $admin = $admin[0];
                $admin_id = $admin['user_id'];
            }

            $selected_id = $this->input->post('administrator') ? $this->input->post('administrator') : $admin_id;
            $users_select = $this->_get_users_select($users, $selected_id);

            $this->load->view('template/standard', array(
                'title'     => 'Create a new stage',
                'content'   => $this->load->view('processdesigner/editor_stage',
                        array(
                            'action'       => "processdesigner/edit_stage/{$stage_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'stages_table' => $stages_table,
                            'users_table'  => $users_table,
                            'users_select' => $users_select,
                            'location'     => "processdesigner/view_stage/{$stage_id}"
                ), TRUE)
            ));
        }
        else
        {
            $this->load->model('processdesigner_model');

            $name = $this->input->post('name');
            $description = $this->input->post('description');
            $previous_stages = array();
            $stages = $this->processdesigner_model->get_stages($process_id);
            foreach($stages as $stage)
            {
                if($this->input->post('stage'.$stage['stage_id']))
                {
                    $previous_stages[] = $stage['stage_id'];
                }
            }

            $jointype = $this->input->post('jointtype');
            switch($jointype)
            {
                case 'AND':
                    $jointype = JOIN_TYPE_AND;
                    break;
                case 'OR':
                    $jointype = JOIN_TYPE_OR;
                    break;
                case 'NONE';
                    $jointype = JOIN_TYPE_NONE;
                    break;
                default:
                    $jointype = JOIN_TYPE_NONE;
                    break;
            }

            $splittype = $this->input->post('splittype');
            switch($splittype)
            {
                case 'AND':
                    $splittype = SPLIT_TYPE_AND;
                    break;
                case 'OR':
                    $splittype = SPLIT_TYPE_OR;
                    break;
                case 'NONE':
                   $splittype = SPLIT_TYPE_NONE;
                   break;
                default:
                    $splittype = SPLIT_TYPE_NONE;
                    break;
            }

            $admin = $this->input->post('administrator');
            $participants = array();
            $users = $this->users_model->all_users();

            foreach($users as $user)
            {
                if($this->input->post('user'.$user['user_id']) && $user['user_id'] != $admin)
                {
                    $participants[] = $user['user_id'];
                }
            }

            $stage_id = $this->processdesigner_model->update_stage($stage['stage_id'], $process_id, $name, $description,
                                    $previous_stages, $jointype, $splittype, $admin, $participants);

            redirect("processdesigner/view_process/{$process_id}");
        }
    }

    function edit_contribution($contribution_id)
    {
        $this->load->model('processdesigner_model');
        $stage = $this->processdesigner_model->get_owner_stage($contribution_id);
        if(!$stage)
        {
            redirect('home/main');
        }
        $process = $this->processdesigner_model->get_owner_process($stage_id);
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }
        $contribution = $this->processdesigner_model->get_contributiondata($contribution_id);
        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('contribution_rules') == FALSE)
        {
            $name = $this->input->post('name') ? $this->input->post('name') : $contribution['contribution_title'];
            $description = $this->input->post('description') ? $this->input->post('description') : $contribution['contribution_description'];

            $this->load->view('template/standard', array(
                'title'     => 'Create a new stage',
                'content'   => $this->load->view('processdesigner/editor_contribution',
                        array(
                            'action'       => "processdesigner/edit_contribution/{$stage_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'location'     => "processdesigner/view_contribution/{$contribution_id}"
                ), TRUE)
            ));
        }
        else
        {
            $name = $this->input->post('name');
            $description = $this->input->post('description');

            $this->processdesigner_model->update_contribution($contribution_id, $stage['stage_id'], $name, $description);
            redirect("processdesigner/view_stage/{$stage_id}");
        }
    }

    function edit_attribute($attribute_id)
    {
        $this->load->model('processdesigner_model');

        $contribution = $this->processdesigner_model->get_owner_contribution($attribute_id);

        if(!$contribution)
        {
            redirect('home/main');
        }

        $stage = $this->processdesigner_model->get_owner_stage($contribution['contribution_id']);

        if(!$stage)
        {
            redirect('home/main');
        }

        $process = $this->processdesigner_model->get_owner_process($stage['stage_id']);

        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }

        $this->form_validation->set_error_delimiters('<p class="error">', '</p>');

        if($this->form_validation->run('attribute_rules') == FALSE)
        {
            $attribute = $this->processdesigner_model->get_attributedata($attribute_id);
            $name = $this->input->post('name') ? $this->input->post('name') : $attribute['attribute_name'];
            $description = $this->input->post('description') ? $this->input->post('description') : $attribute['attribute_description'];
            $checked = $this->input->post('optional') ? 'checked="ckecked"' :
                    $attribute['optional'] == 1 ? 'checked="checked"' : '';

            $this->load->view('template/standard', array(
                'title'     => 'Create a new attribute',
                'content'   => $this->load->view('processdesigner/editor_attribute',
                        array(
                            'action'       => "processdesigner/edit_attribute/{$attribute_id}",
                            'name'         => $name,
                            'description'  => $description,
                            'checked'      => $checked,
                            'location'     => "processdesigner/view_attribute/{$attribute_id}"
                ), TRUE)
            ));
        }
        else
        {
            $name = $this->input->post('name');
            $description = $this->input->post('description');
            $type = $this->input->post('attribute_type');
            $optional = $this->input->post('optional') ? 1 : 0;

            $this->processdesigner_model->update_attribute($attribute_id, $contribution['contribution_id'],
                                                                     $name, $description, $type, $optional);
            redirect("processdesigner/view_contribution/{$contribution['contribution_id']}");
        }
    }

    /*************************************************************************/

    //DELETE

    function delete_process($process_id)
    {
        if(!$this->_checkAccess($process_id))
        {
            redirect("processdesigner/view_process/{$process_id}");
        }

        $this->load->model('processdesigner_model');
        $this->processdesigner_model->delete_process($process_id);
        redirect("home/main");
    }

    function delete_stage($stage_id) 
    {
        $this->load->model('processdesigner_model');
        $process = $this->processdesigner_model->get_owner_process($stage_id);        
        if(!$process || !$this->_checkAccess($process_id))
        {
            redirect("home/main");
        }

        $process_id = $process['process_id'];
        $this->processdesigner_model->delete_stage($stage_id);
        redirect("processdesigner/view_process/{$process_id}");
    }

    function delete_contribution($contribution_id)
    {
        $this->load->model('processdesigner_model');
        $stage = $this->processdesigner_model->get_owner_stage($contribution_id);
        if(!$stage)
        {
            redirect('home/main');
        }
        $process = $this->processdesigner_model->get_owner_process($stage['stage_id']);
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }
        $this->processdesigner_model->delete_contribution($contribution_id);
        redirect("processdesigner/view_stage/{$stage['stage_id']}");
    }

    function delete_attribute($attribute_id)
    {
        $this->load->model('processdesigner_model');
        $contribution =  $this->processdesigner_model->get_owner_contribution($attribute_id);
        if(!$contribution)
        {
            redirect('home/main');
        }
        $stage = $this->processdesigner_model->get_owner_stage($contribution['contribution_id']);
        if(!$stage)
        {
            redirect('home/main');
        }
        $process = $this->processdesigner_model->get_owner_process($stage['stage_id']);
        if(!$process || !$this->_checkAccess($process['process_id']))
        {
            redirect('home/main');
        }
        echo 'autorized';
        $this->processdesigner_model->delete_attribute($attribute_id);
        redirect("processdesigner/view_contribution/{$contribution['contribution_id']}");
    }

    /*************************************************************************/
}

?>